<template>
	<view class="content">
		<u-navbar :custom-back="goback">
			<view class="slot-wrap">
				<u-search
					:placeholder="defaultKeyword"
					v-model="keyword"
					:height="50"
					:input-style="{
						height: '50rpx'
					}"
					:action-style="{
						width: '118rpx',
						height: '50rpx',
						lineHeight: '50rpx',
						backgroundColor: keyword == '' ? '#DFDFDF' : '#EE0F1B',
						borderRadius: '60rpx',
						color: keyword == '' ? '#787882' : '#ffffff'
					}"
					@clear="doclear"
					@change="inputChange"
					@search="doSearch(false)"
					@custom="doSearch(false)"
				></u-search>
			</view>
		</u-navbar>
		<!-- </view> -->
		<view class="search-keyword">
			<!-- 搜索关键字 -->
			<!-- 		<scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
				<block v-for="(row, index) in keywordList" :key="index">
					<view class="keyword-entry" hover-class="keyword-entry-tap">
						<view class="keyword-text" @tap.stop="doSearch(keywordList[index].keyword)"><rich-text :nodes="row.htmlStr"></rich-text></view>
						<view class="keyword-img" @tap.stop="setKeyword(keywordList[index].keyword)"><image src="/static/image/back.png"></image></view>
					</view>
				</block>
			</scroll-view> -->
			<!-- 历史搜索 -->
			<scroll-view class="keyword-box" v-show="hisshow" scroll-y>
				<view class="keyword-block" v-if="oldKeywordList.length > 0">
					<view class="keyword-list-header">
						<view style="font-weight: 600;">搜索历史</view>
						<view><image @tap="oldDelete" src="/static/image/delete.png"></image></view>
					</view>
					<view class="keyword">
						<view v-for="(keyword, index) in oldKeywordList" @tap="doSearch(keyword)" :key="index">{{ keyword }}</view>
					</view>
				</view>
				<view class="keyword-block">
					<view class="keyword-list-header">
						<view style="font-weight: 600;">大家都在搜</view>
						<view><image @tap="hotToggle" :src="'/static/image/attention' + forbid + '.png'"></image></view>
					</view>
					<view class="keyword" v-if="forbid == ''">
						<view v-for="(keyword, index) in hotKeywordList" @tap="doSearch(keyword)" :key="index">{{ keyword }}</view>
					</view>
					<view class="hide-hot-tis" v-else><view>当前搜热门搜索已隐藏</view></view>
				</view>
			</scroll-view>
		</view>
		<!-- 搜索结果商品列表 -->
		<view class="goodsbox" v-if="goodsshow">
			<block v-for="(item, index) in hotgoods" :key="index">
				<view class="goodsli">
					<u-image :border-radius="16" width="200rpx" height="200rpx" :src="item.pict_url" @click="gogoodsinfo(item)"></u-image>
					<view class="hot_right">
						<view class="right_top">
							<text class="tag">热门</text>
							<text class="u-line-1 goods_title" @click="gogoodsinfo(item)">{{ item.title }}</text>
						</view>
						<view class="shop">{{ item.shop_title }}</view>
						<view class="platform">
							<view class="littleplatform">{{ item.user_type == 1 ? '天猫' : '淘宝' }} ￥{{ item.reserve_price }}</view>
							<view class="coupon" v-if="item.coupon_amount != ''" @click="getcoupon(item.coupon_share_url)">{{ item.coupon_amount }}元劵</view>
							<view class="butie">补贴{{ item.money }}</view>
						</view>
						<view class="sales">
							<view class="sales_left">
								<text class="hotone">到手价</text>
								<view class="endprice">
									￥
									<text class="u-font-18">{{ item.zk_final_price }}</text>
								</view>
							</view>
							<view class="sales_right">
								<view>
									已抢
									<text>{{ item.tk_total_sales }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</block>
		</view>
		<u-modal v-model="modelshow" :show-title="false" :show-cancel-button="true" content="确定清除历史搜索记录?" @confirm="confirm"></u-modal>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
export default {
	data() {
		return {
			goodsshow: false,
			modelshow: false,
			// showaction: false,
			defaultKeyword: '',
			keyword: '',
			oldKeywordList: [],
			hotKeywordList: [],
			keywordList: [],
			forbid: '',
			isShowKeywordList: false,
			hisshow: true,
			hotgoods: [
				// {
				// 	item_id: 576475157528, //商品id
				// 	pict_url: 'https://img.alicdn.com/bao/uploaded/i3/797362626/O1CN01IFgyd81VGkhIdzQa1_!!0-item_pic.jpg', //商品主图
				// 	title: '2020年新款反季轻薄宽圆领羽绒服女保暖内胆短款外套秋冬女装无领', //标题
				// 	shop_title: '麦酷麦库旗舰店', //店铺名称
				// 	user_type: 1, //店铺类型（天猫，淘宝）
				// 	reserve_price: '299', //原价
				// 	zk_final_price: '109.9', //卷后价
				// 	tk_total_sales: '567', //销量
				// 	coupon_share_url:
				// 		'//uland.taobao.com/coupon/edetail?优惠卷地址e=c7p1q%2FaVhosNfLV8niU3RxrSI%2FOabn6qNg4Gqf8CT4AKuDLwELihnUdSPzAkgbjde%2FLs5MnnUzR64JewJRWx%2F2qulQl923jbc0aeblGjHeoQzju3KstaoUeSZgfE%2Bo1d%2Bgbu282mGh%2B3GXpSbfs48pwPDYCBUNbotX3SO%2BNRny5h%2FrazpsTK3%2B2EH9ZkW0infjHMNTxsYKQCGruttYDvNg%3D%3D&&app_pvid=59590_11.132.118.167_614_1602661928720&ptl=floorId:2836;app_pvid:59590_11.132.118.167_614_1602661928720;tpp_pvid:100_11.139.248.194_4961_7191602661928722673&xId=5j8xxZWxs2e2bJmDQaSTZwdQmmwQt0VTKvfguLW6OJYQhlkMZ42jM1iJXbxDrfg9TOcXMbITjNU782MVSVF0mY8PZJDSuNEKkDcYMQaobRiP&union_lens=lensId%3AMAPI%401602661928%400b8476a7_0ea8_17526184f5e_cf30%4001',
				// 	coupon_amount: '40', //优惠卷面值
				// 	money: 994.05 //补贴金额（券后价*佣金比例*系统用户分成比例）
				// },
				// {
				// 	item_id: 576475157528, //商品id
				// 	pict_url: 'https://img.alicdn.com/bao/uploaded/i3/797362626/O1CN01IFgyd81VGkhIdzQa1_!!0-item_pic.jpg', //商品主图
				// 	title: '2020年新款反季轻薄宽圆领羽绒服女保暖内胆短款外套秋冬女装无领', //标题
				// 	shop_title: '麦酷麦库旗舰店', //店铺名称
				// 	user_type: 1, //店铺类型（天猫，淘宝）
				// 	reserve_price: '299', //原价
				// 	zk_final_price: '109.9', //卷后价
				// 	tk_total_sales: '567', //销量
				// 	coupon_share_url:
				// 		'//uland.taobao.com/coupon/edetail?优惠卷地址e=c7p1q%2FaVhosNfLV8niU3RxrSI%2FOabn6qNg4Gqf8CT4AKuDLwELihnUdSPzAkgbjde%2FLs5MnnUzR64JewJRWx%2F2qulQl923jbc0aeblGjHeoQzju3KstaoUeSZgfE%2Bo1d%2Bgbu282mGh%2B3GXpSbfs48pwPDYCBUNbotX3SO%2BNRny5h%2FrazpsTK3%2B2EH9ZkW0infjHMNTxsYKQCGruttYDvNg%3D%3D&&app_pvid=59590_11.132.118.167_614_1602661928720&ptl=floorId:2836;app_pvid:59590_11.132.118.167_614_1602661928720;tpp_pvid:100_11.139.248.194_4961_7191602661928722673&xId=5j8xxZWxs2e2bJmDQaSTZwdQmmwQt0VTKvfguLW6OJYQhlkMZ42jM1iJXbxDrfg9TOcXMbITjNU782MVSVF0mY8PZJDSuNEKkDcYMQaobRiP&union_lens=lensId%3AMAPI%401602661928%400b8476a7_0ea8_17526184f5e_cf30%4001',
				// 	coupon_amount: '40', //优惠卷面值
				// 	money: 994.05 //补贴金额（券后价*佣金比例*系统用户分成比例）
				// }
			]
		};
	},
	onLoad(option) {
		console.log(option);
		if (option.search) {
			let id = option.search;
			this.keyword = id;
		}
		this.init();
	},
	onReady() {
		this.doSearch(this.keyword);
	},
	watch: {
		keyword: function(val) {
			if (val !== '') {
				// this.showaction = true;
			} else {
				this.doclear();
			}
		},
		isShowKeywordList: function(val) {
			if (val == true) {
				// this.isShowKeywordList=false
				this.goodsshow = false;
				this.hisshow = false;
			}
		}
	},
	components: {},
	methods: {
		getcoupon(url) {
			// #ifdef APP-PLUS
			plus.runtime.openURL(url);
			// #endif
			// #ifdef H5
			window.open(url);
			// #endif
		},
		dorebaterel(search) {
			this.$u.api
				.dorebaterel({
					search: search
				})
				.then(res => {
					// console.log(res);
					if (res.code == 200) {
						this.hotgoods = res.data;

						this.isShowKeywordList = false; //关闭关键字列表
						this.hisshow = false; //关闭历史搜索
						this.goodsshow = true; //商品列表展示
						console.log(this.hotgoods);
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						});
					}
				
				})
				.catch(err => {
					console.log('err',err);
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error'
					});
				});
		},
		gogoodsinfo(item) {
			uni.navigateTo({
				url: '/pages/goodsrebate/goodsinfo/goodsinfo?item=' + encodeURIComponent(JSON.stringify(item)),
				animationType: 'pop-in',
				animationDuration: 300
			});
		},
		goback() {
			uni.navigateBack({
				delta: 1,
				animationType: 'pop-out',
				animationDuration: 200
			});
		},
		init() {
			this.loadDefaultKeyword();
			this.loadOldKeyword();
			this.loadHotKeyword();
		},
		blur() {
			uni.hideKeyboard();
		},
		//加载默认搜索关键字
		loadDefaultKeyword() {
			this.defaultKeyword = '默认关键字';
		},
		//加载历史搜索,自动读取本地Storage
		loadOldKeyword() {
			uni.getStorage({
				key: 'OldKeys',
				success: res => {
					var OldKeys = JSON.parse(res.data);
					this.oldKeywordList = OldKeys;
				}
			});
		},
		//加载热门搜索
		loadHotKeyword() {
			this.hotKeywordList = ['键盘', '鼠标', '显示器', '电脑主机', '蓝牙音箱', '笔记本电脑', '鼠标垫', 'USB', 'USB3.0'];
		},
		//监听输入
		inputChange(event) {
			//兼容引入组件时传入参数情况
			var keyword = event.detail ? event.detail.value : event;
			if (!keyword) {
				this.keywordList = [];
				this.isShowKeywordList = false;
				return;
			}
			this.isShowKeywordList = true;
			//以下示例截取淘宝的关键字，请替换成你的接口
			// uni.request({
			// 	url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword, //仅为示例
			// 	success: res => {
			// 		console.log(res);
			let res = [
				// ['演示关键字', '101177.06213046666'],
				// ['演示关键字', '1076212.627516825'],
				// ['演示关键字', '734354.738939753'],
				// ['演示关键字 演示关键字', '145088.6276189526'],
				// ['演示关键字', '720403.2155311541'],
				// ['演示关键字', '148389.7834453509'],
				// ['演示关键字 演示关键字', '258231.93791041904'],
				// ['演示关键字', '96720.90784652666'],
				// ['演示关键字', '420669.3942629288']
			];
			this.keywordList = [];
			this.keywordList = this.drawCorrelativeKeyword(res, keyword);
			// 	}
			// });
		},
		doclear() {
			this.keyword = '';
			this.isShowKeywordList = false;
			this.goodsshow = false;
			this.hisshow = true;
		},
		//高亮关键字
		drawCorrelativeKeyword(keywords, keyword) {
			var len = keywords.length,
				keywordArr = [];
			for (var i = 0; i < len; i++) {
				var row = keywords[i];
				//定义高亮#9f9f9f
				var html = row[0].replace(keyword, "<span style='color: #9f9f9f;'>" + keyword + '</span>');
				html = '<div>' + html + '</div>';
				var tmpObj = {
					keyword: row[0],
					htmlStr: html
				};
				keywordArr.push(tmpObj);
			}
			return keywordArr;
		},
		//顶置关键字
		setKeyword(index) {
			this.keyword = this.keywordList[index].keyword;
		},
		//清除历史搜索
		oldDelete() {
			this.modelshow = true;
			// uni.showModal({
			// 	content: '确定清除历史搜索记录？',
			// 	success: (res) => {
			// 		if (res.confirm) {
			// 			console.log('用户点击确定');
			// 			this.oldKeywordList = [];
			// 			uni.removeStorage({
			// 				key: 'OldKeys'
			// 			});
			// 		} else if (res.cancel) {
			// 			console.log('用户点击取消');
			// 		}
			// 	}
			// });
		},
		confirm() {
			this.oldKeywordList = [];
			uni.removeStorage({
				key: 'OldKeys'
			});
		},
		//热门搜索开关
		hotToggle() {
			this.forbid = this.forbid ? '' : '_forbid';
		},
		//执行搜索
		doSearch(keyword) {
			keyword = keyword === false ? this.keyword : keyword;
			this.keyword = keyword;
			console.log('this.keyword', this.keyword);
			this.dorebaterel(this.keyword);
			if (this.keyword == '') {
				return false;
			}
			this.saveKeyword(keyword); //保存为历史

			//以下是示例跳转淘宝搜索，可自己实现搜索逻辑
			/*
				//#ifdef APP-PLUS
				plus.runtime.openURL(encodeURI('taobao://s.taobao.com/search?q=' + keyword));
				//#endif
				//#ifdef H5
				window.location.href = 'taobao://s.taobao.com/search?q=' + keyword
				//#endif
			*/
		},
		//保存关键字到历史记录
		saveKeyword(keyword) {
			uni.getStorage({
				key: 'OldKeys',
				success: res => {
					var OldKeys = JSON.parse(res.data);
					var findIndex = OldKeys.indexOf(keyword);
					if (findIndex == -1) {
						OldKeys.unshift(keyword);
					} else {
						OldKeys.splice(findIndex, 1);
						OldKeys.unshift(keyword);
					}
					//最多10个纪录
					OldKeys.length > 10 && OldKeys.pop();
					uni.setStorage({
						key: 'OldKeys',
						data: JSON.stringify(OldKeys)
					});
					this.oldKeywordList = OldKeys; //更新历史搜索
				},
				fail: e => {
					var OldKeys = [keyword];
					uni.setStorage({
						key: 'OldKeys',
						data: JSON.stringify(OldKeys)
					});
					this.oldKeywordList = OldKeys; //更新历史搜索
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
view {
	display: block;
}

.keyword-list-box {
	height: calc(100vh - 110upx);
	padding-top: 10upx;
	border-radius: 20upx 20upx 0 0;
	background-color: #fff;
}
.keyword-entry-tap {
	background-color: #eee;
}
.keyword-entry {
	width: 100%;
	height: 80upx;
	margin: 0 3%;
	font-size: 30upx;
	color: #333;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: solid 1upx #e7e7e7;
}
.keyword-entry image {
	width: 60upx;
	height: 60upx;
}
.keyword-entry .keyword-text,
.keyword-entry .keyword-img {
	height: 80upx;
	display: flex;
	align-items: center;
}
.keyword-entry .keyword-text {
	width: 90%;
}
.keyword-entry .keyword-img {
	width: 10%;
	justify-content: center;
}
.keyword-box {
	// height: calc(100vh - 110upx);
	border-radius: 20upx 20upx 0 0;
	background-color: #fff;
}
.keyword-box .keyword-block {
	padding: 10upx 0;
}
.keyword-box .keyword-block .keyword-list-header {
	width: 100%;
	padding: 10upx 3%;
	font-size: 27upx;
	color: #333;
	display: flex;
	justify-content: space-between;
}
.keyword-box .keyword-block .keyword-list-header image {
	width: 40upx;
	height: 40upx;
}
.keyword-box .keyword-block .keyword {
	width: 100%;
	padding: 3px 3%;
	display: flex;
	flex-flow: wrap;
	justify-content: flex-start;
}
.keyword-box .keyword-block .hide-hot-tis {
	display: flex;
	justify-content: center;
	font-size: 28upx;
	color: #6b6b6b;
}
.keyword-box .keyword-block .keyword > view {
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 60upx;
	padding: 0 20upx;
	margin: 10upx 20upx 10upx 0;
	height: 60upx;
	font-size: 28upx;
	background-color: rgb(242, 242, 242);
	color: #6b6b6b;
}
.slot-wrap::v-deep {
	display: flex;
	align-items: center;
	flex: 1;
	padding-right: 20rpx;
	.uni-input-placeholder {
		left: 0rpx;
	}
	.uni-input-input {
		text-indent: 0rpx;
	}
}
.goodsbox {
	.goodsli {
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-top: 32rpx;
		.hot_right {
			.right_top {
				display: flex;
				align-items: center;
				.tag {
					display: inline-block;
					width: 74rpx;
					height: 38rpx;
					line-height: 38rpx;
					background-color: #fdbaba;
					text-align: center;
					border-radius: 5px;
					color: #ee0f1b;
					margin-right: 22rpx;
				}
				.goods_title {
					display: inline-block;
					width: 362rpx;
					color: #101010;
					font-size: 26rpx;
					font-weight: 600;
				}
			}
			.shop {
				color: #787882;
				font-size: 24rpx;
				padding: 10rpx 0;
			}
			.platform {
				color: #787882;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				font-size: 24rpx;
				margin-bottom: 10rpx;
				.littleplatform {
					padding-right: 16rpx;
				}
				.coupon {
					// width: 100rpx;
					height: 40rpx;
					line-height: 40rpx;
					background-color: #ff452d;
					text-align: center;
					border-radius: 10rpx;
					color: #ffffff;
					padding: 0 10rpx;
					margin-right: 16rpx;
				}
				.butie {
					// width: 100rpx;
					height: 40rpx;
					line-height: 40rpx;
					background-color: #fdbaba;
					text-align: center;
					border-radius: 10rpx;
					color: #ee0f1b;
					padding: 0 10rpx;
				}
			}
			.sales {
				height: 50rpx;
				line-height: 50rpx;
				display: flex;
				justify-content: space-between;
				align-items: flex-end;
				.sales_left {
					display: flex;
					justify-content: flex-start;
					align-items: flex-end;
					.hotone {
						color: #ff8787;
					}
					.endprice {
						color: #ee0f1b;
						vertical-align: text-bottom;
						display: flex;
						align-items: flex-end;
					}
				}
				.sales_right {
					color: #787882;
					font-size: 24rpx;
				}
			}
		}
	}
}
</style>
